package hk.polyu.dds;

import java.util.Date;

import android.hardware.*;
import android.location.*;
import android.os.*;
import android.app.*;
import android.content.Context;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;

public class TouchLogger extends Activity implements SensorEventListener, LocationListener{
	
	private SensorManager 	mSensorManager;
	private LocationManager mLocationManager;
	
	private Sensor 			mAccelerometer;
	private Sensor			mGyroscope;
	
	private static long 	mSmpCnt = 0;
	
	Logger 					mLog = null;
	
	Button mBtnStart, mBtnStop;
	TextView mTvTouchDisp;
	AlertDialog	mDlg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_touch_logger);
		
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        
        // Sensor Init
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        
        // make sure GPS is enabled and can log speed.
        if(! mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        	Toast.makeText( this, "GPS is NOT on!!!", Toast.LENGTH_LONG).show();
        	//this.finish();
        }
        else { // wait for gps
	        AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder.setMessage("Waiting for GPS signal...");
	        builder.setTitle("Wait");
	        mDlg = builder.create();
	        mDlg.show();
	        
	        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,	this);
        }
		
		mBtnStart = (Button)this.findViewById(R.id.touch_log_start);
		mBtnStop = (Button)this.findViewById(R.id.touch_log_stop);
		mTvTouchDisp = (TextView)this.findViewById(R.id.tvTouchDisp);
		
		mBtnStart.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				startSample(0);
				mBtnStart.setEnabled(false);
				mBtnStop.setEnabled(true);
				
			}
		});
		
		mBtnStop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				stopSample();
				mBtnStart.setEnabled(true);
				mBtnStop.setEnabled(false);
				
			}
		});
		
		
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_touch_logger, menu);
		return true;
	}
	
	
    public void startSample(int mode) {
    	
    	mSmpCnt = 0;
    	
		String [] list = new String[1];
		list[0] = "touch";

		try {
			mLog = new Logger(
					getApplicationContext(), 
					new Date(),
					list);
			
			mLog.open();
			} catch (Exception e) {
				e.printStackTrace();
			}

		mSensorManager.registerListener(TouchLogger.this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
		//Remove gyro for performance.
		mSensorManager.registerListener(TouchLogger.this, mGyroscope, SensorManager.SENSOR_DELAY_FASTEST);
		
		Log.d("polyu", "Sample Started");
		this.mTvTouchDisp.setText("Sample Started");
    }
    
    public void stopSample() {
    	
		mSensorManager.unregisterListener(TouchLogger.this);
		mLocationManager.removeUpdates(this);
    	
    	try {
    		if(mLog != null) {
    			mLog.close();
    			mLog = null;
    		}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		
		Log.d("polyu", "Sample Stoped");
		this.mTvTouchDisp.setText("Sample Stopped");
    }

	@Override
	public void onLocationChanged(Location loc) {
		
		Log.d("polyu", "Location changed");
		
		if(! loc.hasSpeed()) {
			Toast.makeText( this, "No Speed", Toast.LENGTH_LONG).show();
			return ;
		}
		else {
			Log.d("polyu", String.valueOf(loc.getSpeed()));
			if (mDlg.isShowing()) {
				mDlg.dismiss();	
			}
		}
		
		float [] data  = new float[4];
		data[0] = (float)loc.getSpeed();
		data[1] = (float)loc.getBearing();
		data[2] = (float)loc.getLatitude();
		data[3] = (float)loc.getLongitude(); 
		
		if (mLog != null) {
			this.mLog.append("touch", 0, data);
		}
		
	}

	@Override
	public void onProviderDisabled(String arg0) {}

	@Override
	public void onProviderEnabled(String arg0) {}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {}

	@Override
	public void onSensorChanged(SensorEvent event) {
		
    	int type = event.sensor.getType();
    	float [] olddata = event.values.clone();
    	float [] data  = new float[4];
		data[0] = olddata[0];
		data[1] = olddata[1];;
		data[2] = olddata[2];;
		data[3] = 0.0f; 
  
    	//String disp = String.format("x=%+.3f,\ty=%+.3f,\tz=%+.3f", data[0], data[1], data[2]);
    	if (this.mLog != null) {
    		this.mLog.append("touch", type, data);
    		mSmpCnt++;
    		if (mSmpCnt % 5000 == 0) {
    			this.mTvTouchDisp.setText("Logging items: " + mSmpCnt);
    		}
    	}
	}

}
